package br.org.ifrr.repository;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.org.ifrr.model.Empresa;
import br.org.ifrr.repository.filter.EmpresaFilter;

public class Empresas implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@Inject
	private EntityManager manager;

	public Empresa guardar(Empresa empresa) {
		return manager.merge(empresa);
	}
	
	public Empresa porId(Long id) {
		return manager.find(Empresa.class, id);
	}
	
	
	public Empresa porCnpj(String cnpj) {

		try {
			return manager.createQuery("from Empresa where upper(cnpj) = :cnpj",Empresa.class)
					.setParameter("cnpj", cnpj.toUpperCase()).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	
	@SuppressWarnings("unchecked")
	public List<Empresa> filtrados(EmpresaFilter filtro) {
		Session session = manager.unwrap(Session.class);
		Criteria criteria = session.createCriteria(Empresa.class);

		if (StringUtils.isNotBlank(filtro.getNome())) {
			criteria.add(Restrictions.ilike("nome", filtro.getNome(),
					MatchMode.ANYWHERE));
		}

		return criteria.addOrder(Order.asc("nome")).list();
	}
	
	public List<Empresa> porEmpresa(String nome) {

		return this.manager.createQuery("from Empresa where upper(nome) like :nome",	Empresa.class)
				.setParameter("nome", nome.toUpperCase() + "%")
				.getResultList();
	}
}

